<template>
  <div id="echarts1" ref="container" class="echarts-container" :style="`height:${props.height}px`"></div>
</template>
<script setup lang="ts" name="doughnutChart">

import { ref, inject, onBeforeUnmount , defineProps } from 'vue';
const props = defineProps({
  height:{
    type:Number,
    default:0
  }
})
// 获取echart挂载的DOM节点
const container = ref();

// 定义延时器指针对象，便于组件实例销毁的时候以便清除
const timer = ref();

// 通过 inject 接收Echarts
const Echarts = inject('$echarts');
const getFontSize:any = inject('$getfontSize');

// 或
// 通过Vue全局注册方式获取
// const {proxy}: any = getCurrentInstance();


const initEchartsOneFn = () => {
  // echarts初始化
  const myChart = (Echarts as any).init(container.value);

  // 或
  // let myChart = proxy.$echarts.init(container.value);

  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: 'middle',
      left: 'right',
      align: "auto",
      orient:'vertical',
      itemWidth:getFontSize(28),
      itemHeight:getFontSize(20),
      textStyle:{
        color:'#FFFFFF',
        fontSize:getFontSize(20)
      }
    },
    series: [
      {
        name: '',
        type: 'pie',
        radius: ['40%', '70%'],
        center:['30%', '50%'],
        avoidLabelOverlap: false,
        percentPrecision:0,
        label: {
          show: true,
          position: 'inside',
          color: '#FFFFFF',
          formatter:'{d}%',
          fontSize:getFontSize(20)
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold'
          }
        },
        data: [
          {
            value: 7265,
            name: '生产数量：7265',
            itemStyle: {
              color: '#6f5599',
            }
          },
          {
            value: 145,
            name: '不良数量：145',
            itemStyle: {
              color: '#d0914c'
            }
          },
        ]
      }
    ]
  };

  myChart.setOption(option);

  // 根据页面大小自动响应图表大小
  window.addEventListener("resize", function () {
    myChart.resize();
  });
}

// 判断定时器是否存在
if (timer.value) {
  clearTimeout(timer.value);
}

// 绑定定时器，销毁的时候再次清除
timer.value = setTimeout(() => initEchartsOneFn(), 1000);

// 组件实例销毁前清除延时器对象
onBeforeUnmount(() => {
  if (timer.value) clearTimeout(timer.value);
});
</script>

<style lang="scss"  scoped>
#echarts1 {
  width: 100%;
  height: 160px;
}
</style>